package vip.liux.contracts.models.point;

import org.springframework.stereotype.Component;
import vip.liux.contracts.repositories.point.IPointsAccountRepository;

import java.math.BigDecimal;

@Component
public class PointsAccountDomainService {

    private final IPointsAccountRepository userPointsAccountRepository;

    public PointsAccountDomainService(IPointsAccountRepository userPointsAccountRepository) {
        this.userPointsAccountRepository = userPointsAccountRepository;
    }

    /**
     * 获取用户积分账户
     *
     * @param userId 用户ID
     * @return 积分账户实体
     */
    public PointsAccount getAccount(Long userId) {
        return userPointsAccountRepository.findByUserId(userId).orElseGet(() -> {
            PointsAccount account = new PointsAccount();
            account.setUserId(userId);
            account.setAvailablePoints(BigDecimal.ZERO);
            account.setFrozenPoints(BigDecimal.ZERO);
            account.setExpiredPoints(BigDecimal.ZERO);
            userPointsAccountRepository.save(account);
            return account;
        });
    }

    /**
     * 增加可用积分
     *
     * @param userId 用户ID
     * @param points 积分数量
     * @return 积分交易记录
     */
    public PointsAccount addAvailablePoints(Long userId, BigDecimal points) {
        PointsAccount account = getAccount(userId);
        account.setAvailablePoints(account.getAvailablePoints().add(points));
        userPointsAccountRepository.save(account);
        return account;
    }

    /**
     * 冻结积分
     *
     * @param userId 用户ID
     * @param points 积分数量
     * @return 冻结交易记录
     */
    public PointsAccount freezePoints(Long userId, BigDecimal points) {
        PointsAccount account = getAccount(userId);
        account.freezePoints(points);
        userPointsAccountRepository.save(account);
        return account;
    }
}